<?php
class UsersController extends Controller {
    public $viewClass = 'Smarty';
    public $uses = array('');
	function index() {
		$this->set('hello', 'Hello bac Ho!');
	}
    function login() {
    	$arrError = array();
		$userInfo = array();
		$sessionUser = $this->Session->read('UserInfo');
		$email = '';
		if (!empty($sessionUser)) {
			$this->redirect('/');
		}
		if ($this->request->is('post')) {
			$requestData = $this->request->data;
			$email = $requestData('email');
			// check blank
			if (empty($requestData['email']) || trim($requestData['email']) == '') {
				$arrError[] = 'Email must be not blank';
			}
			if (empty($requestData['password'])  || trim($requestData['password']) == '') {
				$arrError[] = 'Password must be not blank';
			}		
			if (empty($arrError)) {
				// user not exist
				$userInfo = $this->UsersModel->findByEmail(trim($requestData['email']));
				if (empty($userInfo)) {
					$arrError[] = 'User is not exist';
				}
			}
			// wrong pass
			if (empty($arrError)) {
				if ($userInfo['UsersModel']['password'] != md5(trim($requestData['password']))) {
					$arrError[] = 'Wrong password';
				}
			} 
			if (empty($arrError)) {
					// everything OK, set session
				$this->Session->write('UserInfo', $userInfo);
				$this->redirect('/');
			}
		}
		$this->set('loginScreen', '1');
		$this->set('email', $email);
		$this->set('arrError', $arrError);
		$this->render('/Users/login');
    }


    function logout() {
        // destroy session
        $this->Session->delete('UserInfo');
        $this->redirect('/login');
    }
}
